package com.example.casper.Experiment2024;

import android.content.Context;
import android.os.Bundle;

import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.casper.Experiment2024.data.BookDetailsActivity;
import com.example.casper.Experiment2024.data.DataBank;
import com.example.casper.Experiment2024.data.Book;
import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link BookListFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class BookListFragment extends Fragment {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER


    // TODO: Rename and change types of parameters


    public BookListFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.

     //* @param param1 Parameter 1.
    // * @param param2 Parameter 2.
     * @return A new instance of fragment BookListFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static BookListFragment newInstance() {
        BookListFragment fragment = new BookListFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View rootViewer = inflater.inflate(R.layout.fragment_book_list, container, false);
        RecyclerView recyclerView = rootViewer.findViewById(R.id.recycler_view_the_books);
        recyclerView.setLayoutManager(new LinearLayoutManager(this.getContext()));
        DataBank databank=new DataBank(this.getContext());
        bookList= databank.readBooks();
        if(bookList.isEmpty()) bookList=getListBooks();
        adapter = new RecyclerViewBookAdapter(bookList, this.getContext());
        recyclerView.setAdapter(adapter);
        registerForContextMenu(recyclerView);
        return rootViewer;
    }
    ActivityResultLauncher<Intent> addItemLauncher;
    ActivityResultLauncher<Intent> updateItemLauncher;
    List<Book> bookList = new ArrayList<>();
    RecyclerViewBookAdapter adapter;

    public boolean onContextItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case 0:
                Intent intent = new Intent(this.getContext(), BookDetailsActivity.class);
                intent.putExtra("position",item.getOrder());
                addItemLauncher.launch(intent);
                break;
            case 1:
                AlertDialog.Builder builder = new AlertDialog.Builder(this.getContext());
                builder.setTitle("Delete Data");
                builder.setMessage("Are you sure you want to delete this data?");
                builder.setPositiveButton("Yes", (dialog, which) -> {
                    bookList.remove(item.getOrder());
                    adapter.notifyItemRemoved(item.getOrder());
                    DataBank databank=new DataBank(BookListFragment.this.getContext());
                    databank.saveBooks(bookList);
                });
                builder.setNegativeButton("No", (dialog, which) -> {
                });
                builder.create().show();
                break;
            case 2:
                Intent intentUpdate = new Intent(BookListFragment.this.getContext(), BookDetailsActivity.class);
                Book book= bookList.get(item.getOrder());
                intentUpdate.putExtra("title",book.getTitle());
                intentUpdate.putExtra("coverResourceId",book.getCoverResourceId());
                intentUpdate.putExtra("position",item.getOrder());
                updateItemLauncher.launch(intentUpdate);
                break;
            default:
                return super.onContextItemSelected(item);
        }
        return true;
    }

    @Override
    public  void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addItemLauncher = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                result -> {
                    if (result.getResultCode() == Activity.RESULT_OK) {
                        Intent data = result.getData();
                        assert data != null;
                        String title = data.getStringExtra("title"); // 获取返回的数据
                        int coverResourceId = data.getIntExtra("coverResourceId",R.drawable.book_no_name); // 获取返回的数据
                        int position = data.getIntExtra("position",0)+1;
                        bookList.add(position,new Book(title, coverResourceId));
                        adapter.notifyItemInserted(position);
                        DataBank databank=new DataBank(this.getContext());
                        databank.saveBooks(bookList);
                    }
                }
        );
        updateItemLauncher = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                result -> {
                    if (result.getResultCode() == Activity.RESULT_OK) {
                        Intent data = result.getData();
                        assert data != null;
                        int position = data.getIntExtra("position",0);
                        String title = data.getStringExtra("title"); // 获取返回的数据
                        int coverResourceId = data.getIntExtra("coverResourceId",R.drawable.book_no_name);

                        Book book = bookList.get(position);
                        book.setTitle(title);
                        book.setCoverResourceId(coverResourceId);
                        adapter.notifyItemChanged(position);
                        DataBank databank=new DataBank(this.getContext());
                        databank.saveBooks(bookList);
                    }
                }
        );

    }



    public static class RecyclerViewBookAdapter extends RecyclerView.Adapter<RecyclerViewBookAdapter.BookViewHolder> {

        private final List<Book> bookList;
        private final Context context;

        public RecyclerViewBookAdapter(List<Book> bookList, Context context) {
            this.bookList = bookList;
            this.context = context;
        }

        @NonNull
        @Override
        public BookViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(context).inflate(R.layout.item_layout, parent, false);
            return new BookViewHolder(view);
        }

        @Override
        public void onBindViewHolder(@NonNull BookViewHolder holder, int position) {
            Book book = bookList.get(position);
            holder.titleTextView.setText(book.getTitle());
            holder.coverImageView.setImageResource(book.getCoverResourceId());
        }

        @Override
        public int getItemCount() {
            return bookList.size();
        }

        public static class BookViewHolder extends RecyclerView.ViewHolder implements View.OnCreateContextMenuListener{
            ImageView coverImageView;
            TextView titleTextView;

            public BookViewHolder(@NonNull View itemView) {
                super(itemView);
                coverImageView = itemView.findViewById(R.id.image_view_book_cover);
                titleTextView = itemView.findViewById(R.id.text_view_book_name);
                itemView.setOnCreateContextMenuListener(this);
            }

            @Override
            public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
            menu.setHeaderTitle("具体操作");
            menu.add(0, 0, this.getAdapterPosition(), "添加" + this.getAdapterPosition());
            menu.add(0, 1, this.getAdapterPosition(), "删除" + this.getAdapterPosition());
            menu.add(0, 2, this.getAdapterPosition(), "修改" + this.getAdapterPosition());
            }

        }
    }

    private List<Book> getListBooks() {

        bookList.add(new Book("创新工程实践", R.drawable.book_no_name));
        bookList.add(new Book("软件项目管理案例教程（第3版）", R.drawable.book_2));
        bookList.add(new Book("信息安全数学基础（第2版）", R.drawable.book_1));
        return bookList;
    }
}